import { access } from '@/api';
import modal from '@/utils/modal';
import { message } from 'antd';
import ReadAccessKey from '../components/readAccessKey';
import { DataType } from '../constant';

export function readAccessKey(
  record: DataType,
  title?: string,
  cb?: () => void,
) {
  return modal({
    title: title || '查看AccessKey',
    width: 520,
    content: <ReadAccessKey record={record} />,
    type: 'confirm',
    callback: () => {
      cb?.();
    },
  });
}

export function createAccessKey(
  userId: string,
  setFresh: (value: boolean) => void,
) {
  return access.createAccess(userId).then((res) => {
    readAccessKey(res.data, '创建AccessKey', () => setFresh(true));
  });
}

export function disableAccessKey(
  record: DataType,
  userId: string,
  setFresh: (value: boolean) => void,
) {
  return modal({
    title: `确认要禁用AccessKey “${record.accessKey}”吗?`,
    type: 'confirm',
    classname: 'dangerModal',
    okText: '禁用',
    content: '该操作无法进行复原，请谨慎操作。',
    callback: () => {
      access
        .disableAccess(userId, record.accessKey)
        .then((res: any) => {
          if (res.code === 200) {
            message.success('禁用成功');
            return setFresh(true);
          }
          throw new Error(res.errmsg || '禁用失败');
        })
        .catch((err: any) => {
          message.error(err.message);
        });
    },
  });
}
